package com.htgd.gardenexpo.controller;

import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.service.GeConAnnouncementAccessService;
import com.htgd.gardenexpo.service.GeConAnnouncementFeedbackService;
import com.htgd.gardenexpo.service.GeConAnnouncementService;
import com.htgd.gardenexpo.service.GeConAnnouncementUploadService;
import com.htgd.gardenexpo.utils.GetAmazonS3Client;
import com.htgd.gardenexpo.utils.SecurityParameter;
import com.htgd.gardenexpo.utils.UniteUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author ：hejing
 * @date ：Created in 2021/5/24 15:18
 * @description：公告管理
 * @menu: 公告管理
 * @modified By：`
 * @version: 1.0
 */
@Api(tags = "公告管理")
@RestController
@RequestMapping("/api/announcement")
public class AnnouncementController {

    @Value("${upload.absolute.url}")
    public String absolute_url;
    @Value("${upload.url}")
    public String upload_url;
    @Value("${local.url}")
    public String local_url;
    @Value("${spring.file-storage.aws-s3[0].bucket-name}")
    public String bucket_name;

    @Resource
    private GeConAnnouncementService geConAnnouncementService;
    @Resource
    private GeConAnnouncementUploadService geConAnnouncementUploadService;
    @Resource
    private GeConAnnouncementFeedbackService geConAnnouncementFeedbackService;
    @Resource
    private GeConAnnouncementAccessService geConAnnouncementAccessService;

    @Autowired
    private FileStorageService fileStorageService;

    @Resource
    private GetAmazonS3Client getAmazonS3Client;

    /**
     * 新增公告信息
     */
    @PostMapping(value = "/add")
    public CommonResult<JSONObject> add(@RequestBody GeConAnnouncement geConAnnouncement) {
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geConAnnouncementService.insert(geConAnnouncement);
            if (!geConAnnouncement.getUploadIds().equals("")) {
                for (String uploadId : geConAnnouncement.getUploadIds().split(",")) {
                    GeConAnnouncementUpload geConAnnouncementUpload = geConAnnouncementUploadService.queryById(Integer.parseInt(uploadId));
                    geConAnnouncementUpload.setAnnouncementId(geConAnnouncement.getAnnouncementId());
                    geConAnnouncementUploadService.update(geConAnnouncementUpload);
                }
            }
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 上传图片
     */
    @PostMapping(value = "/uploadUserPhoto")
    public String uploadUserPhoto(@RequestParam(value = "file") MultipartFile file) {

        //使用指定的存储平台
        FileInfo fileInfo = fileStorageService.of(file)
                .setPlatform("aws-s3-1")
                .upload();
        return upload_url + fileInfo.getFilename();
    }

    /**
     * 上传文件
     */
    @PostMapping(value = "/uploadFile")
    public GeConAnnouncementUpload uploadFile(@RequestParam(value = "file") MultipartFile file) {

        GeConAnnouncementUpload geConAnnouncementUpload = new GeConAnnouncementUpload();
        String fileName = file.getOriginalFilename();  // 文件名
        geConAnnouncementUpload.setFilename(fileName);
        FileInfo fileInfo = fileStorageService.of(file)
                .setPlatform("aws-s3-1")
                .setSaveFilename(System.currentTimeMillis()+"/"+file.getOriginalFilename())
                .upload();
        geConAnnouncementUpload.setFilePath(upload_url + fileInfo.getFilename());
        geConAnnouncementUploadService.insert(geConAnnouncementUpload);
        return geConAnnouncementUpload;
    }

    /**
     * 编辑公告信息
     */
    @PostMapping(value = "/edit")
    public CommonResult<JSONObject> edit(@RequestBody GeConAnnouncement geConAnnouncement) {
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            String uploadIds = geConAnnouncement.getUploadIds();
            geConAnnouncementService.update(geConAnnouncement);
            if (!uploadIds.equals("") && uploadIds.contains(",")) {
                geConAnnouncementUploadService.deleteByIds(uploadIds.split(","), geConAnnouncement.getAnnouncementId());
                for (String uploadId : uploadIds.split(",")) {
                    GeConAnnouncementUpload geConAnnouncementUpload = geConAnnouncementUploadService.queryById(Integer.parseInt(uploadId));
                    geConAnnouncementUpload.setAnnouncementId(geConAnnouncement.getAnnouncementId());
                    geConAnnouncementUploadService.update(geConAnnouncementUpload);
                }
            } else {
                geConAnnouncementUploadService.deleteByAnnouncementId(geConAnnouncement.getAnnouncementId());
            }
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除公告信息
     */
    @PostMapping(value = "/delete")
    public CommonResult<JSONObject> delete(int announcementId) {
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geConAnnouncementService.deleteById(announcementId);
            List<GeConAnnouncementUpload> list = geConAnnouncementUploadService.queryByAnnouncementId(announcementId);
            for (GeConAnnouncementUpload geConAnnouncementUpload : list) {
                String path = geConAnnouncementUpload.getFilePath().substring(geConAnnouncementUpload.getFilePath().indexOf(bucket_name + "/"), geConAnnouncementUpload.getFilePath().length() - 1);
                getAmazonS3Client.delete(path);
            }
            geConAnnouncementUploadService.deleteByAnnouncementId(announcementId);
            geConAnnouncementFeedbackService.deleteByAnnouncementId(announcementId);
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 批量删除公告
     */
//    @PostMapping(value = "/deleteAll")
    public CommonResult<JSONObject> deleteAll(String announcementIds){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            if (announcementIds!=null&&!announcementIds.equals("")){
                for (String promo:announcementIds.split(",")){
                    int promoId= Integer.parseInt(promo);
                    delete(promoId);
                }
            }

            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 历史公告信息检索列表
     */
    @PostMapping(value = "/list")
    @SecurityParameter
    public CommonResult<List<GeConAnnouncement>> list(@RequestBody PageQuery pageQuery) {
        CommonResult<List<GeConAnnouncement>> result = new CommonResult<>();
        try {
            pageQuery.setPageNum((pageQuery.getPageNum() - 1) * pageQuery.getPageSize());
            List<GeConAnnouncement> list = geConAnnouncementService.getAllAnnouncementByValue(pageQuery);
            if (list != null && list.size() > 1) {
                for (GeConAnnouncement geConAnnouncement : list) {
                    String content=UniteUtils.stripHtml(geConAnnouncement.getAnnouncementContent().toString());
                    if (!content.equals("")){
                        geConAnnouncement.setAnnouncementContent(content.substring(0,content.length()>200?200:content.length()));
                    }else {
                        geConAnnouncement.setAnnouncementContent("");
                    }
                }
            }
            pageQuery.setPageSize(0);
            List<GeConAnnouncement> list1 = geConAnnouncementService.getAllAnnouncementByValueNoContent(pageQuery);
            result.setCode(200);
            result.setData(list);
            result.setMessage(String.valueOf(list1.size()));
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 历史公告信息检索列表
     */
    @PostMapping(value = "/listWx")
    @SecurityParameter
    public CommonResult<List<GeConAnnouncement>> listWx(@RequestBody PageQuery pageQuery) {
        CommonResult<List<GeConAnnouncement>> result = new CommonResult<>();
        try {
            pageQuery.setPageNum((pageQuery.getPageNum() - 1) * pageQuery.getPageSize());
            List<GeConAnnouncement> list = geConAnnouncementService.getAllAnnouncementByValue(pageQuery);
            if (list != null && list.size() > 1) {
                for (GeConAnnouncement geConAnnouncement : list) {
                    String content=UniteUtils.stripHtml(geConAnnouncement.getAnnouncementContent().toString());
                    if (!content.equals("")){
                        geConAnnouncement.setAnnouncementContent(content.substring(0,content.length()>200?200:content.length()));
                    }else {
                        geConAnnouncement.setAnnouncementContent("");
                    }
                }
            }
            pageQuery.setPageSize(0);
            List<GeConAnnouncement> list1 = geConAnnouncementService.getAllAnnouncementByValueNoContent(pageQuery);
            result.setCode(200);
            result.setData(list);
            result.setMessage(String.valueOf(list1.size()));
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 公告信息发布
     */
    @GetMapping(value = "/release")
    public CommonResult<JSONObject> release() {
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 公告信息取消发布
     */
    @GetMapping(value = "/unpublish")
    public CommonResult<JSONObject> unpublish() {
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 公告信息排序
     */
    @GetMapping(value = "/sort")
    public CommonResult<List<Map<String, Object>>> sort() {
        CommonResult<List<Map<String, Object>>> result = new CommonResult<>();
        return result;
    }

    /**
     * 公告信息置顶
     */
    @GetMapping(value = "/top")
    public CommonResult<JSONObject> top() {
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 公告信息轮播列表
     */
    @GetMapping(value = "/carousellist")
    public CommonResult<List<GeConAnnouncement>> carousellist() {
        CommonResult<List<GeConAnnouncement>> result = new CommonResult<>();
        try {
            List<GeConAnnouncement> list = geConAnnouncementService.getAllHomeAnnouncement();
            result.setData(list);
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }


    /**
     * 公告信息审核
     */
    @GetMapping(value = "/review")
    public CommonResult<JSONObject> review(GeConAnnouncement geConAnnouncement) {
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            GeConAnnouncement geConAnnouncement1=geConAnnouncementService.queryById(geConAnnouncement.getAnnouncementId());
            geConAnnouncement1.setStatus(geConAnnouncement.getStatus());
            if (geConAnnouncement.getPublisherId()!=null){
                geConAnnouncement1.setPublisherId(geConAnnouncement.getPublisherId());
            }
            if (geConAnnouncement.getAuthUserId()!=null){
                geConAnnouncement1.setAuthUserId(geConAnnouncement.getAuthUserId());
            }
            String feedback = geConAnnouncement.getFeedback();
            geConAnnouncement1.setReleasetime(new Date());
            geConAnnouncementService.update(geConAnnouncement1);
            if (!feedback.equals("")) {
                GeConAnnouncementFeedback geConAnnouncementFeedback = new GeConAnnouncementFeedback();
                geConAnnouncementFeedback.setAnnouncementId(geConAnnouncement.getAnnouncementId());
                geConAnnouncementFeedback.setContent(feedback);
                geConAnnouncementFeedbackService.insert(geConAnnouncementFeedback);
            }
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 公告信息审核失败反馈
     */
    @GetMapping(value = "/feedbackInfo")
    public CommonResult<List<GeConAnnouncementFeedback>> feedbackInfo(int announcementId) {
        CommonResult<List<GeConAnnouncementFeedback>> result = new CommonResult<>();
        try {
            List<GeConAnnouncementFeedback> list = geConAnnouncementFeedbackService.getinfoByAnnouncementId(announcementId);
            result.setData(list);
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 公告信息详情
     */
    @PostMapping(value = "/details")
    @SecurityParameter
    public CommonResult<Map<String, Object>> details(@RequestBody String s) {
        CommonResult<Map<String, Object>> result = new CommonResult<>();
        try {
            boolean flag1 = s.contains("flag");
            Integer announcementId= JSON.parseObject(s).getInteger("announcementId");
            if(flag1){
                boolean flag= JSON.parseObject(s).getBoolean("flag");
                if(flag){
                    addAccess(s);
                }
            }
            Map<String, Object> map = new HashMap<>();
            GeConAnnouncement geConAnnouncement = geConAnnouncementService.queryById(announcementId);
            map.put("announcement", geConAnnouncement);
            List<GeConAnnouncementUpload> geConAnnouncementUploads = geConAnnouncementUploadService.queryByAnnouncementId(announcementId);
            map.put("upload", geConAnnouncementUploads);
            PageQuery pageQuery = new PageQuery();
            pageQuery.setReviewStatus("3");
            pageQuery.setPageSize(0);
            List<GeConAnnouncement> nlist = geConAnnouncementService.getAllAnnouncementByValueNoContent(pageQuery);
            List<GeConAnnouncement> list = new ArrayList<GeConAnnouncement>();
            for (int i = 0; i < nlist.size(); i++) {
                GeConAnnouncement geConAnnouncement1 = nlist.get(i);
                if (announcementId == geConAnnouncement1.getAnnouncementId()) {
                    if (nlist.size() >= 3) {
                        if (i < nlist.size() - 3) {
                            if (i != 0) {
                                map.put("up", Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            list.add(Conversion(nlist.get(i + 2)));
                            list.add(Conversion(nlist.get(i + 3)));
                            map.put("more", list);
                        } else if (i == nlist.size() - 3) {
                            if (i != 0) {
                                map.put("up",Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            list.add(Conversion(nlist.get(i + 2)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(0)));
                            }
                            map.put("more", list);
                        } else if (i == nlist.size() - 2) {
                            if (i != 0) {
                                map.put("up", Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(0)));
                                list.add(Conversion(nlist.get(1)));
                            }
                            map.put("more", list);
                        } else if (i == nlist.size() - 1) {
                            if (i != 0) {
                                map.put("up",Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", "");
                            list.add(Conversion(nlist.get(0)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(1)));
                            }
                            map.put("more", list);
                        }
                    } else {
                        if (i == 0 && nlist.size() > 1) {
                            map.put("up", "");
                            map.put("down", Conversion(nlist.get(i + 1)));
                        } else if (i == 0 && nlist.size() == 1) {
                            map.put("up", "");
                            map.put("down", "");
                        } else {
                            map.put("up", Conversion(nlist.get(i - 1)));
                            map.put("down", "");
                        }
                        map.put("more", "");
                    }
                    break;
                }
            }
            result.setData(map);
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    public GeConAnnouncement  Conversion(GeConAnnouncement geConAnnouncement){
        GeConAnnouncement geConAnnouncement1=geConAnnouncementService.queryById(geConAnnouncement.getAnnouncementId());
        String content=UniteUtils.stripHtml(geConAnnouncement1.getAnnouncementContent().toString());
        if (!content.equals("")){
            geConAnnouncement1.setAnnouncementContent(content.substring(0,content.length()>200?200:content.length()));
        }else {
            geConAnnouncement1.setAnnouncementContent("");
        }
        return geConAnnouncement1;
    }

    /**
     * 统计公告点击
     */
    @PostMapping("/addAccess")
    @SecurityParameter
    public CommonResult<JSONObject> addAccess(@RequestBody String s){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            Integer announcementId=JSON.parseObject(s).getInteger("announcementId");
            GeConAnnouncementAccess geConAnnouncementAccess = new GeConAnnouncementAccess();
            geConAnnouncementAccess.setAnnouncementId(announcementId);
            geConAnnouncementAccessService.insert(geConAnnouncementAccess);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

}
